package com.fjzx.androidframe.base.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;


/**
 * 基础ViewPager + Fragment 使用的Adapter
 * 使用FragmentStatePagerAdapter，不会在内存中长期持有Fragment引用，对内存使用比较友好
 *
 * @Author xiongyongcong
 */
public class BaseFragmentPagerAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private Fragment mCurrentFragment;

    public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.mFragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments == null ? null : mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments == null ? 0 : mFragments.size();
    }

    /**
     * 返回POSITION_NONE，否则Adapter将会使用的缓存的Fragment，导致notifyDataSetChanged()无效
     */
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    /**
     * 设置当前ViewPager显示的主Fragment
     */
    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        mCurrentFragment = (Fragment) object;
    }

    /**
     * 获取当前ViewPager显示的主Fragment
     */
    public Fragment getCurrentFragment() {
        return mCurrentFragment;
    }

    /**
     * 绑定Fragment
     */
    public void setFragments(List<Fragment> fragments) {
        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }
        this.mFragments = fragments;
        notifyDataSetChanged();
    }
}
